using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Data.SqlClient;
using System.Text;
using System.Drawing.Printing;
using System.Collections.Generic;
using System.Collections.Specialized;

public partial class ReportWizard : System.Web.UI.Page
{
    DataTable dtObj = null;
    HDDatabase hdd = null;
    security hdds = null;
    ScreenReader SR = null;
    DataSet dsPageInfo = null;
    DataSet dsInputInfo = null;
    HtmlTable htProperties;
    string sReportType = "";
    string m_PageSetId = "ps_report";
    bool IsEdit = false;
    string m_PageKey = "";
    string m_Report_id = "";
    List<Stream> m_streams;
    System.Windows.Forms.PrintDialog printDialog1 = new System.Windows.Forms.PrintDialog();
    int m_currentPageIndex = 0;
    bool bExport = false;
    float dReportWidth = 8f;
    double dReportHeight = 11f;
    //DataSet dsReportInput = null;
    string exportType = "";

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
        //Session["dbcon"] = "Data Source=\"CSNSYS063\";User Id=\"test10\";Password=\"test10_123\";Initial Catalog=\"test10\"";
        hdd = new HDDatabase();
        hdds = new security();
        SR = new ScreenReader();

////        HtmlLink link = new HtmlLink();
////        link.Href = "~/"+Session["Theme"].ToString();
////        link.Attributes.Add("rel","stylesheet");
//////link.Attributes.Add("rel", "stylesheet");

////link.Attributes.Add("type", "text/css");

////link.Attributes.Add("href", "~/"+Session["Theme"].ToString()+".css");
 
////Page.Controls.Add(link);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        imgNewWindow.Visible = false;
        if (Request.QueryString["mn"] != null)
            hdds.logMenuClick(Request.QueryString["mn"].ToString());

        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        wz_Report.DisplaySideBar = false;

        //if (Request.QueryString["pgs_id"] != null)
        //    m_PageSetId = Request.QueryString["pgs_id"];

        IsActionMode(); // Added by srivatsan for action 

        if (dsPageInfo == null)
        {
            PageInfoLoad objPIL = new PageInfoLoad();
            dsPageInfo = objPIL.GetPageSetPageCtrlInfo(m_PageSetId);
            DataSet dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("1115c5d9f03853ab"); // ps_report_obj
            DataSet dsPageInfo2 = objPIL.GetPageSetPageCtrlInfo("6e0a8813dec48f1f"); // ps_report_att
            dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
            dsPageInfo.Tables["Page"].Merge(dsPageInfo2.Tables["Page"]);
            dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
            dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo2.Tables["PageCtrl"]);
            dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
            dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo2.Tables["PageKeys"]);
        }

        if (!hdds.getObjectRightsForUser("sy_report_sql", "read")) rbPredefinedObjects.Visible = false;

        if (Request.QueryString["PK"] != null)
        {
            m_PageKey = Request.QueryString["PK"].ToString();
            if (!IsPostBack)
                hf_af_row_id.Value = m_PageKey;
            m_Report_id = hdd.GetColumnValue("select rpt_id from sy_report where af_row_id = '" + m_PageKey + "'");
            if (Request.QueryString["CPY"] != null)
            {
                if (Request.QueryString["CPY"] == "0")
                {
                    wz_Report.HeaderText = "Report Wizard - Copy";
                    IsEdit = false;
                }
                else
                {
                    wz_Report.HeaderText = "Report Wizard - Edit";
                    IsEdit = true;
                }
            }
            else
            {
                wz_Report.HeaderText = "Report Wizard - Edit";
                IsEdit = true;
            }
        }


        if (!Page.IsPostBack)
        {
            getpageicons();
            loadOwneridDropDown();//Added by srivatsan
        }

        CheckForChangeOwner();

        //PageCommonFunctions PCF = new PageCommonFunctions();
        //PCF.AddSearchLink(ref tdownerid, "owner_id", "wz_Report_owner_id", "wz_Report_txt_owner_id", "92");
        string strPK = "";
        if (Request.QueryString["PK"] != null)
        {
            strPK = Request.QueryString["PK"].ToString();
        }
        imgsearch.Attributes.Add("onclick", "javascript:openlookupwindow('wz_Report_owner_id','wz_Report_txt_owner_id','f496930dfe0b690f','" + strPK + "','" + Request.QueryString["pgs_id"].ToString() + "');");

        if (IsEdit)
        {
            if (Session["ReportInput"] != null)
            {
                dsInputInfo = (DataSet)Session["ReportInput"];
                Session["ReportInput"] = null;
            }
        }
        else
            if (!IsPostBack)
            {
                txt_Report_Id.Text = getReportId();
                hf_af_row_id.Value = SR.getHashKey();
            }

        if (!IsPostBack)
        {
            //Session["RedirectLocation"] = Request.UrlReferrer.AbsoluteUri;
            Session["RedirectLocation"] = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();
            MyRDLC myrdlc = new MyRDLC();

            string sBG0 = myrdlc.getCSSPropertyValue(".Grid_Row0", "background-color");
            string sBG1 = myrdlc.getCSSPropertyValue(".Grid_Row1", "background-color");
            if (sBG0 == "") sBG0 = "#FFFFFF";
            rptViewer.BackColor = System.Drawing.ColorTranslator.FromHtml(sBG1);//System.Drawing.ColorTranslator.FromHtml(myrdlc.getCSSPropertyValue(".Dynamic_PageHeaderRow", "background-color"));
            rptViewer.BorderStyle = BorderStyle.None;
            //rptViewer.BorderWidth = System.Web.UI.WebControls.Unit.Point(2);
            //rptViewer.BorderColor = System.Drawing.ColorTranslator.FromHtml(sBG0);
            //imgNewWindow.OnClientClick = "javascript:(window.open('Report.aspx',null,'menubar=no,resizable=no,scrollbars=no')||window).focus();";//height=600,width=800,top=50,left=100
            //CheckEditOperation();
            imgSelectEnableDisable();
            string sSql = "Select * from sy_obj order by object_name asc";
            loadObjectsinCombo(sSql);
            sReportType = "Tabular";
            txtReportName.Focus();
        }
        else
        {
            if (lstSelectedFields.Items.Count > 0)
                showFieldProperties();
            //disableControls();
        }
        //if (hfRName.Value != "")
        //    imgNewWindow.Enabled = true;
        //else
        //    imgNewWindow.Enabled = false;
        checkEditCopyOperation();
        isViewMode();
        if (wz_Report.ActiveStepIndex == 3) 
            if (IsPostBack)
            {
                Hashtable hsParam = new Hashtable();
                hsParam = getParameters("$", ref hsParam);
                hsParam = getParameters("#", ref hsParam);
                DrawParameterTable(ref hsParam);
                SetParameter(ref hsParam);
                hsParam = null;
            }
        
    }
    private void isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                //DynamicDisplayI ddi = new DynamicDisplayI();
                //ddi.disableControls(this);
                //ddi = null;
                Response.Redirect("Report.aspx?pgs_id=" + Request.QueryString["pgs_id"] + "&PK=" + Request.QueryString["PK"]);
            }
    }
    //private void disableControls()
    //{
    //    if (lstSelectedFields.Items.Count == 0)
    //    {
    //        imgDown.Enabled = false;
    //        imgUp.Enabled = false;
    //        imgUnselect.Enabled = false;
    //        imgUnselectAll.Enabled = false;
    //    }

    //    if (lstFields.Items.Count == 0)
    //    {
    //        imgSelect.Enabled = false;
    //        imgSelectAll.Enabled = false;
    //    }
    //}
    private bool checkEditCopyOperation()
    {
        bool blnStatus = true;

        if (!IsPostBack)
        {
            //frmObj = (HtmlForm)this.Master.FindControl("Form1");
            if (Request.QueryString["PK"] != null)
            {
                //m_PageKey = Request.QueryString["PK"].ToString();
                IsEdit = true;
                btnSave.Visible = false;

                if (Request.QueryString["CPY"] != null)
                {
                    if (Request.QueryString["CPY"] == "0")
                    {
                        //btnSave.Visible = true;
                        //btnUpdate.Visible = false;
                        IsEdit = false;
                        ScreenReader SR = new ScreenReader();
                        hf_af_row_id.Value = SR.getHashKey();
                        //TextBox txtID = (TextBox)frmObj.FindControl("ContentPlaceHolder").FindControl("");
                    }
                }
                getData();
                setData(IsEdit);
            }
        }
        return blnStatus;
    }

    private void deleteReport()
    {
        if (hfRName.Value != "")
        {
            if (System.IO.File.Exists(hfRName.Value))
                System.IO.File.Delete(hfRName.Value);
            hfRName.Value = "";
            //imgNewWindow.Enabled = false;
            //Session.Remove("ReportPath");
        }
    }

    private void updateData(ref DataSet dsInput)
    {
        SqlTransaction sqlTrans = null;
        SqlConnection sqlConn = new SqlConnection(Session["dbcon"].ToString());
        sqlConn.Open();
        sqlTrans = sqlConn.BeginTransaction();
        string sSql = "delete from sy_report where af_row_id='" + hf_af_row_id.Value + "'";
        SqlCommand sqlComm = new SqlCommand(sSql);
        sqlComm.Transaction = sqlTrans;
        sqlComm.Connection = sqlConn;
        sqlComm.ExecuteNonQuery();
        sSql = "delete from sy_report_obj where rpt_id='" + hf_af_row_id.Value + "'";
        sqlComm = new SqlCommand(sSql);
        sqlComm.Transaction = sqlTrans;
        sqlComm.Connection = sqlConn;
        sqlComm.ExecuteNonQuery();
        sSql = "delete from sy_report_att where rpt_id='" + hf_af_row_id.Value + "'";
        sqlComm = new SqlCommand(sSql);
        sqlComm.Transaction = sqlTrans;
        sqlComm.Connection = sqlConn;
        sqlComm.ExecuteNonQuery();
        string sCreated_User = GlobalValues.dsAudit.Tables[0].Rows[0]["created_by"].ToString();
        string sCreated_On = GlobalValues.dsAudit.Tables[0].Rows[0]["created_at"].ToString();
        //string sOwner_id = GlobalValues.dsAudit.Tables[0].Rows[0]["owner_id"].ToString(); // Added by srivatsan on June 15 2009 for owner id field
        string sOwner_id = owner_id.Value; // Added by srivatsan on June 15 2009 for owner id field

        Master objMaster = new Master();
        //bool bResult = false;
        if (!objMaster.ProcessOperation(dsPageInfo, dsInputInfo, "INSERT"))
        {
            lblMessage.Text = objMaster.ErrorMessage;
            sqlTrans.Rollback();
        }
        else
        {
            sqlTrans.Commit();

            //sSql = "update sy_report set created_by='" + sCreated_User + "' where af_row_id='" + hf_af_row_id.Value + "'";
            sSql = "update sy_report set owner_id = '" + sOwner_id + "', created_by='" + sCreated_User + "' where af_row_id='" + hf_af_row_id.Value + "'"; // Added by srivatsan on June 15 2009 for owner id field
            sqlComm = new SqlCommand(sSql);
            sqlComm.Connection = sqlConn;
            sqlComm.ExecuteNonQuery();
            sSql = "update sy_report set created_at='" + sCreated_On + "' where af_row_id='" + hf_af_row_id.Value + "'";
            sqlComm = new SqlCommand(sSql);
            sqlComm.Connection = sqlConn;
            sqlComm.ExecuteNonQuery();

            //sSql = "update sy_report_obj set created_by='" + sCreated_User + "' where rpt_id='" + hf_af_row_id.Value + "'";
            // Added by srivatsan on June 15 2009 for owner id field
            sSql = "update sy_report_obj set owner_id ='" + sOwner_id + "',created_by='" + sCreated_User + "' where rpt_id='" + hf_af_row_id.Value + "'";
            sqlComm = new SqlCommand(sSql);
            sqlComm.Connection = sqlConn;
            sqlComm.ExecuteNonQuery();
            sSql = "update sy_report_obj set created_at='" + sCreated_On + "' where rpt_id='" + hf_af_row_id.Value + "'";
            sqlComm = new SqlCommand(sSql);
            sqlComm.Connection = sqlConn;
            sqlComm.ExecuteNonQuery();

            //sSql = "update sy_report_att set created_by='" + sCreated_User + "' where rpt_id='" + hf_af_row_id.Value + "'";
            // Added by srivatsan on June 15 2009 for owner id field
            sSql = "update sy_report_att set owner_id = '" + sOwner_id + "', created_by='" + sCreated_User + "' where rpt_id='" + hf_af_row_id.Value + "'";
            sqlComm = new SqlCommand(sSql);
            sqlComm.Connection = sqlConn;
            sqlComm.ExecuteNonQuery();
            sSql = "update sy_report_att set created_at='" + sCreated_On + "' where rpt_id='" + hf_af_row_id.Value + "'";
            sqlComm = new SqlCommand(sSql);
            sqlComm.Connection = sqlConn;
            sqlComm.ExecuteNonQuery();

            //bResult = true;
        }
        sqlConn.Dispose();
        sqlConn = null;
        sqlTrans.Dispose();
        sqlTrans = null;
        sqlComm.Dispose();
        sqlComm = null;
        //AuditLog AL = new AuditLog();
        //AL.WriteAuditLog(ref dsPageInfo, ref dsInputInfo, "UPDATE", bResult);
        //AL = null;
    }

    protected void wizReport_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        if (!validateOwnerid())
        {
            return;
        }
        if (fillInputData(ref dsInputInfo))
        {
            if (IsEdit)
            {
                updateData(ref dsInputInfo);
            }
            else
            {
                string sOperation = "INSERT";
                Master objMaster = new Master();

                if (!objMaster.ProcessOperation(dsPageInfo, dsInputInfo, sOperation))
                    lblMessage.Text = objMaster.ErrorMessage;
            }
        }
        //deleteReport();        

        if (Session["ReportInput"] != null)
            Session.Remove("ReportInput");

        Response.Redirect(Session["RedirectLocation"].ToString());
    }
    private void setFieldValues()
    {
        DataTable dt = (DataTable)Session["FieldProperties"];
        Session["FieldProperties"] = null;
        if (dsInputInfo != null)
            if (dsInputInfo.Tables["p_sy_report_att"] != null)
                if (dt == null)
                    dt = dsInputInfo.Tables["p_sy_report_att"];
        if (dt != null)
        {
            for (int iCount = 0; iCount < lstSelectedFields.Items.Count; iCount++)
            {
                ListItem li = lstSelectedFields.Items[iCount];
                TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                DataRow[] drr = dt.Select("attrib_id='" + li.Value + "'");

                if (drr.Length != 0)
                {
                    txtBox.Text = drr[0]["caption"].ToString();
                }
            }
            dt.Dispose();
            dt = null;
        }
    }
    protected void wz_Report_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        ImageButton newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
        newWindow.Visible = false;
        if (wz_Report.ActiveStepIndex == 0)  // Added by srivatsan
        {
            //string ownerafrowid = getUseraf_row_idfromUser(txt_owner_id.Text);
            //if (ownerafrowid != "")
            //{
            //    owner_id.Value = ownerafrowid;
            //}
            //else
            //{
            //    lblMessage.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
            //    return;
            //}
        }
        else if (wz_Report.ActiveStepIndex == 1)
        {
            setFieldValues();
        }
        else if (wz_Report.ActiveStepIndex == 2)
        {
            string sReportName = null;
            //string absReportPath = null;

            try
            {
                newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
                newWindow.Visible = true;
                getData();
                if (fillInputData(ref dsInputInfo))
                {
                    imgNewWindow.Enabled = true;
                    if (Session["ReportInput"] == null)
                        Session.Add("ReportInput", dsInputInfo);
                    else
                        Session["ReportInput"] = dsInputInfo;

                    string constr = Session["dbcon"].ToString();
                    string sSql = getSql();
                    sReportName = getReportProperties("rpt_name");
                    if (sReportName == "") sReportName = getReportProperties("rpt_id");
                    //SqlDataSource1.ConnectionString = constr;
                    //SqlDataSource1.SelectCommand = sSql;
                    
                    MyRDLC mrdlc = new MyRDLC();
                    //switch (sReportType.ToLower())
                    //{
                    //    default:
                    //    case "tabular":
                    //        mrdlc.GenerateRdl(absReportPath, sReportName, getReportProperties("rpt_desc"));
                    //        break;
                    //    //    /*case "matrix":
                    //    //        mrdlc.GenerateMatrixRdl(absReportPath);
                    //    //        break;*/
                    //}

                    MemoryStream msReport = null;
                    float dReportWidth = 8.0f;
                    //mrdlc.GenerateReportFromDataset(dsInputInfo, ref msReport, ref dReportWidth);
                    //if (msReport != null)
                    //{
                        //this.Title = sReportName;
                        rptViewer.Reset();
                        rptViewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", "SqlDataSource1"));

                        if (dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "true")
                        {
                            getDataFromSQLandFormat objData = new getDataFromSQLandFormat(sSql);
                            DataTable dt = objData.getData(ref dsInputInfo);
                            dsInputInfo.Tables.Add(dt.Copy()); // Added by srivatsan for datatype alignment;
                            objData = null;
                            if (dt != null)
                            {
                                mrdlc.GenerateReportFromDataset(dsInputInfo, ref msReport, ref dReportWidth, exportType);
                                rptViewer.LocalReport.DataSources.Clear();
                                rptViewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", dt));
                            }
                        }
                        else
                        {
                            getDataFromSQLandFormat objData = new getDataFromSQLandFormat(sSql);
                            DataTable dt1 = objData.getData(ref dsInputInfo);
                            objData = null;
                            dsInputInfo.Tables.Add(dt1.Copy());
                            mrdlc.GenerateReportFromDataset(dsInputInfo, ref msReport, ref dReportWidth, exportType);
                            rptViewer.LocalReport.DataSources.Clear();
                            rptViewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", dt1));
                            dt1.Dispose();
                            dt1 = null;
                        }

                        rptViewer.LocalReport.DisplayName = sReportName;
                        if (msReport != null)
                        {
                        rptViewer.LocalReport.LoadReportDefinition(msReport);
                        }
                        rptViewer.LocalReport.EnableExternalImages = true;
                        //absReportPath = @"D:\MaxBlox\app_frame\report\New_admin_200813144846721.rdlc";
                        //rptViewer.LocalReport.ReportPath = absReportPath;
                        rptViewer.LocalReport.Refresh();
                        msReport.Dispose();
                    }
                    //hfRName.Value = absReportPath;
                    /*if (Session["ReportPath"] == null)
                        Session.Add("ReportPath", absReportPath);
                    else
                        Session["ReportPath"] = absReportPath;*/
                //}
                bool IsExport = getExportValue();
                if (IsExport)
                {
                    lbFF.Visible = true;
                    ddlFileFormat.Visible = true;
                    lnkExport.Visible = true;
                    //lnkPrint.Visible = true;
                }
                else
                {
                    lbFF.Visible = false;
                    ddlFileFormat.Visible = false;
                    lnkExport.Visible = false;
                    //lnkPrint.Visible = false;
                }
            }

            catch (Exception ex)
            {
                lbFF.Visible = false;
                ddlFileFormat.Visible = false;
                lnkExport.Visible = false;
                //lnkPrint.Enabled = false;
                imgNewWindow.Enabled = false;
                LogWriter.WriteLog("Error : " + ex.Message);
                Response.Redirect("Error.aspx");
            }

        }
    }

    private void ProcessDataTable(ref DataTable dtData)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        try
        {
            string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");

            foreach (DataColumn dc in dtData.Columns)
                if (dc.DataType == Type.GetType("System.DateTime"))
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        if (dr[dc.ColumnName] != System.DBNull.Value)
                            dr[dc.ColumnName] = DDI.getUsersDT(dr[dc.ColumnName].ToString(), sUTC_Offset);
                    }
                }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("ProcessDataTable : Error : " + ex.Message);
        }
        finally
        {
            DDI = null;
        }
    }

    private DataTable getDataForReport(string Query)
    {
        DataTable dtData = new DataTable();
        SqlDataAdapter objAdapter = null;
        SqlConnection sqlConn = null;
        SqlCommand command = null;
        try
        {
            sqlConn = new SqlConnection(HttpContext.Current.Session["dbcon"].ToString());
            sqlConn.Open();
            command = sqlConn.CreateCommand();
            command.CommandText = Query;
            objAdapter = new SqlDataAdapter(command);
            objAdapter.Fill(dtData);
            sqlConn.Close();

            //if (dtData.Rows.Count > 0 && dtData.Columns.Contains("created_by"))
            // Added by srivatsan on June 15 2009 for owner id field
            if (dtData.Rows.Count > 0 && dtData.Columns.Contains("owner_id"))
            {
                SecurityFilter SF = new SecurityFilter();
                DataSet dseObj = SF.GetFilterDataset(Query);
                dtData = dseObj.Tables[0].Copy();
                dseObj.Dispose();
                dseObj = null;
            }

            ProcessDataTable(ref dtData);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getDataSet : Error : " + ex.Message);
            dtData = null;
        }

        finally
        {
            objAdapter.Dispose();
            sqlConn.Dispose();
            command.Dispose();
            objAdapter = null;
            sqlConn = null;
            command = null;
        }
        return dtData;
    }

    private DataTable getDataTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("attrib_id");
        dt.Columns.Add("caption");

        return dt;
    }
    private void collectValues()
    {
        DataTable dtValues = getDataTable();
        for (int iCount = 0; iCount < lstSelectedFields.Items.Count; iCount++)
        {
            ListItem li = lstSelectedFields.Items[iCount];

            TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
            string sCaption = "";
            if (txtBox != null)
                sCaption = txtBox.Text;
            else
                sCaption = li.Text;

            DataRow dr = dtValues.NewRow();
            dr["attrib_id"] = li.Value;
            dr["caption"] = sCaption;
            dtValues.Rows.Add(dr);
        }

        Session["FieldProperties"] = dtValues;
    }

    private void collectValuesFromDS()
    {
        DataTable dtValues = getDataTable();

        foreach (DataRow drr in dsInputInfo.Tables["p_sy_report_att"].Rows)
        {
            DataRow dr = dtValues.NewRow();
            dr["attrib_id"] = "[" + drr["object_id"].ToString() + "].[" + drr["attrib_id"].ToString() + "]";
            dr["caption"] = drr["caption"];
            dtValues.Rows.Add(dr);
        }
        Session["FieldProperties"] = dtValues;
    }

    protected void wz_Report_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
    {
        ImageButton newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
        newWindow.Visible = false;
        if (wz_Report.ActiveStepIndex == 3)
            Session["ReportInput"] = null;
        else if (wz_Report.ActiveStepIndex == 2)
            collectValues();
    }
    protected void wz_Report_CancelButtonClick(object sender, EventArgs e)
    {
        //deleteReport();
        Session["FieldProperties"] = null;
        Response.Redirect(Session["RedirectLocation"].ToString());
    }
    protected void wz_Report_ActiveStepChanged(object sender, EventArgs e)
    {
        switch (wz_Report.ActiveStepIndex)
        {
            case 0:
                break;
            case 1:
                //if (cmbObject.Items.Count != 0)
                //populateFields("");
                ImageButton newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
                newWindow.Visible = true;
                //string ownerafrowid = getUseraf_row_idfromUser(txt_owner_id.Text);
                //if (ownerafrowid != "")
                //{
                //    owner_id.Value = ownerafrowid;
                    
                    
                //}
                //else
                //{
                //    lblMessage.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                //    return;
                //}

                
                break;
            case 2:
                if (cmbObject.Text == "--Select an Object--")
                {
                    lblFieldsMsg.Text = "Please select an object";
                    wz_Report.ActiveStepIndex = 1;
                }
                else if (lstSelectedFields.Items.Count == 0)
                {
                    if (rbPredefinedObjects.Checked)
                    {
                        DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + cmbObject.SelectedItem.Value);
                        if (dr != null)
                        {
                            if (!dr["report_base_sql"].ToString().Contains("$") && !dr["report_base_sql"].ToString().Contains("#"))
                            {
                                lblFieldsMsg.Text = "Please select atleast one field to be displayed in the report";
                                wz_Report.ActiveStepIndex = 1;
                            }
                            else
                                wz_Report.ActiveStepIndex = 3;
                        }
                    }
                    else
                    {
                        lblFieldsMsg.Text = "Please select atleast one field to be displayed in the report";
                        wz_Report.ActiveStepIndex = 1;
                    }
                }
                newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
                newWindow.Visible = true;
                break;
            case 3:
                bool isExport = getExportValue();
                if (rbPredefinedObjects.Checked)
                {
                    Hashtable hsParam = new Hashtable();
                    hsParam = getParameters("$", ref hsParam);
                    hsParam = getParameters("#", ref hsParam);
                    DrawParameterTable(ref hsParam);
                    if (hsParam.Count > 0)
                    {
                        lbFF.Visible = false;
                        ddlFileFormat.Visible = false;
                        lnkExport.Visible = false;
                        btn_Generate.Visible = true;
                        rptViewer.Visible = false;
                    }
                    else
                    {
                        if (isExport)
                        {
                            lbFF.Visible = true;
                            ddlFileFormat.Visible = true;
                            lnkExport.Visible = true;
                        }
                        else
                        {
                            lbFF.Visible = false;
                            ddlFileFormat.Visible = false;
                            lnkExport.Visible = false;
                            //lnkPrint.Visible = false;
                        }
                    }
                    hsParam = null;
                }
                else
                {
                    if (isExport)
                    {
                        lbFF.Visible = true;
                        ddlFileFormat.Visible = true;
                        lnkExport.Visible = true;
                    }
                }
                break;
        }
    }
    protected void rbAllObjects_CheckedChanged(object sender, EventArgs e)
    {
        string sSql = "Select * from sy_obj order by object_name asc";
        //string sSql = "Select * from sy_report_base";
        loadObjectsinCombo(sSql);
        lbl_Object.Text = "Choose base object        ";
    }
    protected void rbPredefinedObjects_CheckedChanged(object sender, EventArgs e)
    {
        //string sSql = "Select * from sy_report_sql";
        //loadObjectsinCombo(sSql);
        loadSQLinCombo();
        lbl_Object.Text = "Choose from existing query";
    }
    protected void cmbObject_SelectedIndexChanged(object sender, EventArgs e)
    {
        populateListBox(lstFields);
    }

    private void loadObjectsinCombo(string Sql)
    {
        Sql = applysecurity(Sql);
        dtObj = hdd.GetDataTable(Sql);
        AddDefaultObjects(ref dtObj); //Added by Srivatsan
        lblFieldsMsg.Text = "";
        lblDesc.Text = "";
        lstFields.Items.Clear();
        lstSelectedFields.Items.Clear();
        cmbObject.Items.Clear();
        cmbObject.Items.Add("--Select an Object--");
        foreach (DataRow dr in dtObj.Select("", "object_name asc")) //Mod by srivatsan
        {
            if (hdds.getObjectRightsForUser(dr["object_id"].ToString(), "read"))
            {
                ListItem liObject = new ListItem(dr["object_name"].ToString(), dr["object_id"].ToString());
                cmbObject.Items.Add(liObject);
            }
        }
    }

    private void populateFieldsFromQuery(ListBox Fields)
    {
        try
        {
            lstFields.Items.Clear();
            lstSelectedFields.Items.Clear();
            string sQueryId = cmbObject.SelectedItem.Value;

            DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + sQueryId);
            if (dr != null)
            {
                lblDesc.Text = dr["report_base_desc"].ToString();
                string sSql = dr["report_base_sql"].ToString();
                string sQueryName = cmbObject.SelectedItem.Text;
                if (sSql.Contains("$") || sSql.Contains("#"))
                {
                    dr = null;
                    lstFields.Enabled = false;
                    lstSelectedFields.Enabled = false;
                    imgSelect.Enabled = false;
                    imgUnselect.Enabled = false;
                    imgSelectAll.Enabled = false;
                    imgUnselectAll.Enabled = false;
                    imgUp.Enabled = false;
                    imgDown.Enabled = false;

                    if (IsPostBack) wz_Report.ActiveStepIndex = 3;
                    return;
                }
                else
                {
                    lstFields.Enabled = true;
                    lstSelectedFields.Enabled = true;
                    imgSelect.Enabled = true;
                    imgUnselect.Enabled = true;
                    imgSelectAll.Enabled = true;
                    imgUnselectAll.Enabled = true;
                    imgUp.Enabled = true;
                    imgDown.Enabled = true;
                }

                DataTable dtQuery = null;
                if (sSql != "")
                {
                    dtQuery = hdd.GetDataTable(sSql);
                    if (dtQuery != null)
                    {
                        foreach (DataColumn dc in dtQuery.Columns)
                        {
                            ListItem li = new ListItem("[" + sQueryName + "].[" + dc.ColumnName + "]", "[" + sQueryId + "].[" + dc.ColumnName + "]");
                            Fields.Items.Add(li);//lstSelectedFields.Items.Add(li);
                        }
                        //lstFields.Enabled = false;
                        imgSelect.Enabled = true;
                        imgUnselect.Enabled = false;
                        imgSelectAll.Enabled = true;
                        imgUnselectAll.Enabled = false;
                        imgUp.Enabled = false;
                        imgDown.Enabled = false;
                    }
                }
                dr = null;
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("populateFieldsFromQuery : Error : " + Ex.Message);
        }
    }

    private void loadSQLinCombo()
    {

        string sSql = "Select * from sy_report_sql";

        //sSql = applysecurity(sSql);

        dtObj = hdd.GetDataTable(sSql);
        lblFieldsMsg.Text = "";
        lblDesc.Text = "";
        lstFields.Items.Clear();
        lstSelectedFields.Items.Clear();
        cmbObject.Items.Clear();
        cmbObject.Items.Add("--Select a query--");
        foreach (DataRow dr in dtObj.Select())
        {
            ListItem liObject = new ListItem(dr["report_base_name"].ToString(), dr["report_base_id"].ToString());
            cmbObject.Items.Add(liObject);
        }
    }

    private void populateFields(string ObjectId, ListBox Fields)
    {
        lstFields.Enabled = true;
        lstSelectedFields.Enabled = true;
        imgSelect.Enabled = true;
        imgUnselect.Enabled = true;
        imgSelectAll.Enabled = true;
        imgUnselectAll.Enabled = true;
        imgUp.Enabled = true;
        imgDown.Enabled = true;
        lstFields.Items.Clear();
        lstSelectedFields.Items.Clear();
        string sObjectName = cmbObject.SelectedItem.Text;
        ObjectId = cmbObject.SelectedValue;
        string sSql = "Select * from sy_obj";
        dtObj = hdd.GetDataTable(sSql);
        DataRow[] drr = dtObj.Select("object_id='" + ObjectId + "'");
        if (drr.Length > 0)
        {
            lblDesc.Text = drr[0]["object_description"].ToString();

            sSql = "Select * from sy_obj_mas_detail where object_id = '" + drr[0]["af_row_id"].ToString() + "'";

            DataTable dtFields = hdd.GetDataTable(sSql);

            foreach (DataRow dr in dtFields.Select())
            {
                string sAttrib_Name = "";
                sAttrib_Name = dr["attrib_id"].ToString();

                if (dr["attrib_id"].ToString() != "af_row_id")
                {
                    ListItem liObject = new ListItem("[" + sObjectName + "].[" + sAttrib_Name + "]", "[" + dr["master_obj"].ToString() + "].[" + sAttrib_Name + "]");
                    Fields.Items.Add(liObject);
                }
            }

            sSql = "Select * from sy_obj_att where object_id = '" + drr[0]["af_row_id"].ToString() + "'";

            dtFields = hdd.GetDataTable(sSql);

            foreach (DataRow dr in dtFields.Select())
            {
                string sAttrib_Name = "";
                if (dr["attrib_name"].ToString() == "")
                    sAttrib_Name = dr["attrib_id"].ToString();
                else
                    sAttrib_Name = dr["attrib_name"].ToString();
                if (dr["attrib_id"].ToString() != "af_row_id")
                {
                    ListItem liObject = new ListItem("[" + sObjectName + "].[" + sAttrib_Name + "]", "[" + ObjectId + "].[" + dr["attrib_id"].ToString() + "]");
                    Fields.Items.Add(liObject);
                }
            }
            dtFields.Dispose();
            dtFields = null;
        }
        imgSelect.Enabled = true;
        imgSelectAll.Enabled = true;
    }
    protected void imgSelect_Click(object sender, ImageClickEventArgs e)
    {
        if (lstFields.Items.Count > 0)
        {
            lstSelectedFields.SelectedIndex = -1;
            if (lstFields.SelectedItem != null) //lstFields.Items[0].Selected = true;
            {
                ListItem liSelected = lstFields.SelectedItem;
                lstFields.Items.Remove(liSelected);
                lstSelectedFields.Items.Add(liSelected);
                imgUnselect.Enabled = true;
                imgUnselectAll.Enabled = true;
                imgUp.Enabled = true;
                imgDown.Enabled = true;
                if (lstFields.Items.Count == 0)
                {
                    imgSelect.Enabled = false;
                    imgSelectAll.Enabled = false;
                }
            }
        }
    }
    protected void imgUnselect_Click(object sender, ImageClickEventArgs e)
    {
        if (lstSelectedFields.Items.Count > 0)
        {
            lstFields.SelectedIndex = -1;
            if (lstSelectedFields.SelectedItem != null) //lstSelectedFields.Items[0].Selected = true;
            {
                ListItem liSelected = lstSelectedFields.SelectedItem;
                lstSelectedFields.Items.Remove(liSelected);
                lstFields.Items.Add(liSelected);
                imgSelect.Enabled = true;
                imgSelectAll.Enabled = true;
                if (lstSelectedFields.Items.Count == 0)
                {
                    imgUnselect.Enabled = false;
                    imgUnselectAll.Enabled = false;
                    imgUp.Enabled = false;
                    imgDown.Enabled = false;
                }
            }
        }
    }

    private void setTxtBoxTxt()
    {
    }

    private void showFieldProperties()
    {
        btnSave.Enabled = false;
        HtmlForm frmObj = (HtmlForm)this.Master.FindControl("Form1");
        htProperties = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("tblproperties");
        //HtmlTableCell htcField = (HtmlTableCell) frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("td_field");
        HtmlTableRow htr = new HtmlTableRow();
        HtmlTableCell htc = new HtmlTableCell();
        Label lbl = new Label();

        if (htProperties != null)
        {
            #region Header Region Commented
            //htc.Width = "100px";
            //htc.Align = "Center";
            //lbl.Text = "Attribute Id";
            //htc.Controls.Add(lbl);
            //htr.Cells.Add(htc);
            //htc = new HtmlTableCell();
            //htc.Width = "100px";
            //htc.Align = "Center";
            //lbl = new Label();
            //lbl.Text = "Attribute Name";
            //htc.Controls.Add(lbl);
            //htr.Cells.Add(htc);
            //htc = new HtmlTableCell();
            //htc.Width = "100px";
            //htc.Align = "Center";
            //lbl = new Label();
            //lbl.Text = "Caption";
            //htc.Controls.Add(lbl);
            //htr.Cells.Add(htc);
            //htProperties.Rows.Add(htr); 
            #endregion
            for (int iCount = 0; iCount < lstSelectedFields.Items.Count; iCount++)
            {
                //btnSave.Enabled = true;
                ListItem li = lstSelectedFields.Items[iCount];
                htr = new HtmlTableRow();
                lbl = new Label();
                lbl.ID = "attrib_id_" + li.Value;
                lbl.Text = li.Value;
                lbl.CssClass = "defaultFont";
                lbl.Font.Size = FontUnit.Point(8);
                htc = new HtmlTableCell();
                htc.Controls.Add(lbl);
                htr.Cells.Add(htc);

                lbl = new Label();
                lbl.ID = "attrib_name_" + li.Text + SR.getHashKey();
                lbl.Text = li.Text;
                lbl.CssClass = "defaultFont";
                lbl.Font.Size = FontUnit.Point(8);
                htc = new HtmlTableCell();
                htc.Controls.Add(lbl);
                htr.Cells.Add(htc);

                string sAttributeName = "";
                if (IsEdit) sAttributeName = getFieldCaption(li.Value);
                if (sAttributeName == "")
                    sAttributeName = li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3));

                TextBox txtBox = new TextBox();
                txtBox.Text = sAttributeName;
                txtBox.ID = "txt_" + li.Value;
                txtBox.Width = 250;
                txtBox.BorderStyle = BorderStyle.None;
                //txtBox.BorderColor = System.Drawing.Color.Gainsboro;
                txtBox.CssClass = "defaultFont";
                txtBox.Font.Size = FontUnit.Point(8);

                htc = new HtmlTableCell();
                htc.Controls.Add(txtBox);
                htr.Cells.Add(htc);
                htr.Height = "25px";
                int iRow = (iCount + 1) % 2;
                htr.Attributes.Add("Class", "Grid_Row" + iRow.ToString());
                htProperties.Rows.Add(htr);
            }
            //htcField.Controls.Add(ht);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (SaveData())
            lblMessage.Text = "Data inserted successfully";
    }

    private void fillDefaultColumns(ref DataRow dr, string sCurrentDate)
    {
        string ownerafrowid = getUseraf_row_idfromUser(txt_owner_id.Text);
        if (dr["created_by"] == DBNull.Value)
        {
            dr["created_by"] = Session["user_afrowid"].ToString();
            //dr["owner_id"] = Session["user_afrowid"].ToString(); // Added by srivatsan on June 15 2009 for owner id field
            //dr["owner_id"] = ddownerid.SelectedValue;


            if (ownerafrowid != "")
            {
                owner_id.Value = ownerafrowid;
                dr["owner_id"] = owner_id.Value;
            }
            else
            {
                lblMessage.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                return;
            }


            

            dr["created_at"] = sCurrentDate;
        }
        if (IsEdit)
        {
            dr["created_by"] = GlobalValues.dsAudit.Tables[0].Rows[0]["created_by"];
            //dr["owner_id"] = GlobalValues.dsAudit.Tables[0].Rows[0]["owner_id"];// Added by srivatsan on June 15 2009 for owner id field
            //dr["owner_id"] = ddownerid.SelectedValue;
            if (ownerafrowid != "")
            {
                owner_id.Value = ownerafrowid;
                dr["owner_id"] = owner_id.Value;
            }
            else
            {
                lblMessage.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                return;
            }
            dr["created_at"] = GlobalValues.dsAudit.Tables[0].Rows[0]["created_at"];
        }
        dr["modified_by"] = Session["user_afrowid"].ToString();
        dr["modified_at"] = sCurrentDate;
    }

    private bool fillInputData(ref DataSet dsInputInfo)
    {
        bool bReturn = true;
        try
        {
            HtmlForm frmObj = (HtmlForm)this.Master.FindControl("Form1");
            HtmlTable htProperties = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("tblproperties");
            ScreenReader SR = new ScreenReader();
            if (htProperties != null)
            {
                string sPageSetId = m_PageSetId;
                string sReportId = "";
                #region MyRegion
                //if (dsPageInfo == null)
                //{
                //    PageInfoLoad objPIL = new PageInfoLoad();
                //    dsPageInfo = objPIL.GetPageSetPageCtrlInfo(sPageSetId);
                //} 
                #endregion

                //if (dsInputInfo == null)
                //{

                //getInputDataSet(ref dsInputInfo);
                ScreenReader objSR = new ScreenReader();
                dsInputInfo = new DataSet();
                objSR.CreatePageDataTable(dsInputInfo, dsPageInfo.Tables["Page"], dsPageInfo.Tables["PageCtrl"]);

                sReportId = hdd.GetColumnValue("Select max(rpt_id) from sy_report");
                if (!IsEdit)
                {
                    if (sReportId == "")
                        sReportId = "1";
                    else
                        sReportId = Convert.ToString(Convert.ToInt16(sReportId) + 1);
                }
                else
                    sReportId = m_Report_id;

                string sCurrentDate = DateTime.Now.ToString();

                if (dsInputInfo.Tables["p_sy_report"] != null)
                {
                    DataRow drReport = dsInputInfo.Tables["p_sy_report"].NewRow();
                    if (drReport != null)
                    {
                        drReport["af_row_id"] = hf_af_row_id.Value;
                        drReport["rpt_id"] = sReportId;
                        drReport["rpt_name"] = txtReportName.Text.Trim();
                        drReport["rpt_desc"] = txtReportDesc.Text.Trim();
                        if (rbTabular.Checked)
                            drReport["rpt_type"] = rbTabular.Text;
                        else if (rbMatrix.Checked)
                            drReport["rpt_type"] = rbMatrix.Text;
                        else if (rbMasterDetail.Checked)
                            drReport["rpt_type"] = rbMasterDetail.Text;
                        //drReport["created_date"] = DateTime.Now();
                        if (rbPredefinedObjects.Checked)
                            drReport["rpt_base_object"] = "true";
                        else
                            drReport["rpt_base_object"] = "false";

                        fillDefaultColumns(ref drReport, sCurrentDate);
                    }
                    dsInputInfo.Tables["p_sy_report"].Rows.Add(drReport);
                }

                if (dsInputInfo.Tables["p_sy_report_obj"] != null)
                {
                    DataRow drReport = dsInputInfo.Tables["p_sy_report_obj"].NewRow();
                    if (drReport != null)
                    {
                        if (IsEdit)
                        {
                            string sTemp = GlobalValues.dsAudit.Tables["p_sy_report_obj"].Rows[0]["af_row_id"].ToString();
                            if (sTemp == "") sTemp = SR.getHashKey();
                            drReport["af_row_id"] = sTemp;
                        }
                        else
                            drReport["af_row_id"] = SR.getHashKey();
                        drReport["rpt_id"] = hf_af_row_id.Value;
                        drReport["object_id"] = cmbObject.SelectedValue;
                        //drReport["created_date"] = DateTime.Now();

                        fillDefaultColumns(ref drReport, sCurrentDate);
                    }
                    dsInputInfo.Tables["p_sy_report_obj"].Rows.Add(drReport);
                }

                if (dsInputInfo.Tables["p_sy_report_att"] != null)
                {
                    ExecuteVariableQueryAndGetFields();
                    for (int iCount = 0; iCount < lstSelectedFields.Items.Count; iCount++)
                    {
                        DataRow drReport = dsInputInfo.Tables["p_sy_report_att"].NewRow();
                        if (drReport != null)
                        {
                            ListItem li = lstSelectedFields.Items[iCount];

                            TextBox txtBox = (TextBox)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                            string sCaption = "";
                            if (txtBox != null)
                                sCaption = txtBox.Text;
                            else
                                sCaption = li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3));// li.Text;
                            string sId = li.Value;

                            drReport["rpt_id"] = hf_af_row_id.Value;
                            drReport["attrib_id"] = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));
                            drReport["object_id"] = sId.Substring(1, sId.IndexOf("]") - 1);
                            if (IsEdit)
                            {
                                string sTemp = "";
                                DataRow[] drr = GlobalValues.dsAudit.Tables["p_sy_report_att"].Select("object_id='" + drReport["object_id"].ToString() + "' and attrib_id='" + drReport["attrib_id"].ToString() + "'");
                                if (drr.Length > 0)
                                    sTemp = drr[0]["af_row_id"].ToString();
                                if (sTemp == "") sTemp = SR.getHashKey();
                                drReport["af_row_id"] = sTemp;
                            }
                            else
                                drReport["af_row_id"] = SR.getHashKey();
                            drReport["caption"] = sCaption;
                            drReport["attrib_sequence"] = iCount;

                            fillDefaultColumns(ref drReport, sCurrentDate);

                            dsInputInfo.Tables["p_sy_report_att"].Rows.Add(drReport);
                        }
                    }
                }
                //}
            }
        }

        catch (Exception ex)
        {
            bReturn = false;
            LogWriter.WriteLog(this.Title + " : Error : " + ex.Message);
        }
        return bReturn;
    }

    private void ExecuteVariableQueryAndGetFields()
    {
        try
        {
            if (dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "true")
            {
                DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + cmbObject.SelectedItem.Value);
                if (dr != null)
                {
                    lblDesc.Text = dr["report_base_desc"].ToString();
                    string sSql = dr["report_base_sql"].ToString();
                    string sQueryName = cmbObject.SelectedItem.Text;
                    if (sSql.Contains("$") || sSql.Contains("#"))
                    {
                        SqlConnection sqlConn = new SqlConnection(Session["dbcon"].ToString());
                        sqlConn.Open();
                        /*string*/ sSql = getSql(); ;
                        SqlCommand sqlComm = new SqlCommand(sSql);
                        sqlComm.Connection = sqlConn;
                        SqlDataReader sqlReader = sqlComm.ExecuteReader(CommandBehavior.SchemaOnly);
                        DataTable dtSchema = sqlReader.GetSchemaTable();
                        if (dtSchema != null)
                        {
                            for (int iCount = 0; iCount <= dtSchema.Rows.Count; iCount++)
                            {
                                //foreach (DataRow dr in dtSchema.Rows)
                                //{
                                DataRow drS = dtSchema.Rows[iCount];
                                DataRow drReport = dsInputInfo.Tables["p_sy_report_att"].NewRow();
                                if (drReport != null)
                                {
                                    string sCaption = drS["ColumnName"].ToString();
                                    //string sId = li.Value;

                                    drReport["rpt_id"] = hf_af_row_id.Value;
                                    drReport["attrib_id"] = sCaption;
                                    drReport["object_id"] = cmbObject.SelectedItem.Value;
                                    if (IsEdit)
                                    {
                                        string sTemp = "";
                                        DataRow[] drr = GlobalValues.dsAudit.Tables["p_sy_report_att"].Select("object_id='" + drReport["object_id"].ToString() + "' and attrib_id='" + drReport["attrib_id"].ToString() + "'");
                                        if (drr.Length > 0)
                                            sTemp = drr[0]["af_row_id"].ToString();
                                        if (sTemp == "") sTemp = SR.getHashKey();
                                        drReport["af_row_id"] = sTemp;
                                    }
                                    else
                                        drReport["af_row_id"] = SR.getHashKey();
                                    drReport["caption"] = sCaption;
                                    drReport["attrib_sequence"] = iCount;

                                    fillDefaultColumns(ref drReport, DateTime.Now.ToString());

                                    dsInputInfo.Tables["p_sy_report_att"].Rows.Add(drReport);
                                }
                            }
                        }
                        dtSchema.Dispose();
                        dtSchema = null;
                        sqlReader.Close();
                        sqlReader = null;
                        sqlComm.Dispose();
                        sqlComm = null;
                        sqlConn.Close();
                        sqlConn.Dispose();
                        sqlConn = null;
                    }
                }
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("" + Ex.Message);
        }
    }


    protected void rbTabular_CheckedChanged(object sender, EventArgs e)
    {
        sReportType = rbTabular.Text;
    }
    protected void rbMatrix_CheckedChanged(object sender, EventArgs e)
    {
        sReportType = rbMatrix.Text;
    }
    protected void rbMasterDetail_CheckedChanged(object sender, EventArgs e)
    {
        sReportType = rbMasterDetail.Text;
    }

    private bool SaveData()
    {
        bool bReturn = true;
        Master objMaster = new Master();
        try
        {
            if (fillInputData(ref dsInputInfo))
            {
                if(!validateOwnerid())
                {
                    return false;
                }
                bReturn = objMaster.ProcessOperation(dsPageInfo, dsInputInfo, "INSERT");

                if (!bReturn)
                    lblMessage.Text = objMaster.ErrorMessage;
            }
        }

        catch (Exception ex)
        {
            bReturn = false;
            LogWriter.WriteLog(this.Title + " : Error : " + ex.Message);
        }

        return bReturn;
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        bool bReturn = true;
        Master objMaster = new Master();
        try
        {
            if (fillInputData(ref dsInputInfo))
            {
                bReturn = objMaster.ProcessOperation(dsPageInfo, dsInputInfo, "UPDATE");

                if (!bReturn)
                    lblMessage.Text = objMaster.ErrorMessage;
            }
        }
        catch (Exception ex)
        {
            bReturn = false;
            LogWriter.WriteLog(this.Title + " : Error : " + ex.Message);
        }
    }
    private void CheckEditOperation()
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["PK"] != null)
                btnSave.Visible = false;
            else
                btnUpdate.Visible = false;
        }
    }
    protected void btnView_Click(object sender, EventArgs e)
    {
        if (fillInputData(ref dsInputInfo))
        {
            if (IsEdit)
            {
                if (Session["ReportInput"] == null)
                    Session.Add("ReportInput", dsInputInfo);
                else
                    Session["ReportInput"] = dsInputInfo;
            }
            string popupScript = "<script language='javascript'>" +
                "window.open('ReportFrame.aspx','ReportWindow'," +
                "'menubar=no,resizable=yes,scrollbars=no," +
                "height=600,width=800,top=50,left=100')" + "</script>";

            Page.RegisterStartupScript("ReportWindow", popupScript);
            System.Type ty = popupScript.GetType();
        }
    }

    protected void Page_PreRenderComplete(object sender, EventArgs e)
    {
        //Session.Add("ReportInput", dsInputInfo);
    }

    private string getAttributeName(string AttributeId)
    {
        string sAttributeName = "";
        string sSql = "Select attrib_name from sy_obj_att where attrib_id = '" + AttributeId + "'";
        sAttributeName = hdd.GetColumnValue(sSql);
        return sAttributeName;
    }
    protected void imgUp_Click(object sender, ImageClickEventArgs e)
    {
        int iSelectedIndex = lstSelectedFields.SelectedIndex;
        if (iSelectedIndex != -1)
        {
            if (iSelectedIndex != 0)
            {
                ListItem li = lstSelectedFields.SelectedItem;
                lstSelectedFields.Items.RemoveAt(iSelectedIndex);
                lstSelectedFields.Items.Insert(iSelectedIndex - 1, li);
            }
        }
    }
    protected void imgDown_Click(object sender, ImageClickEventArgs e)
    {
        int iSelectedIndex = lstSelectedFields.SelectedIndex;
        if (iSelectedIndex != -1)
        {
            if (iSelectedIndex != lstSelectedFields.Items.Count - 1)
            {
                ListItem li = lstSelectedFields.SelectedItem;
                lstSelectedFields.Items.RemoveAt(iSelectedIndex);
                lstSelectedFields.Items.Insert(iSelectedIndex + 1, li);
            }
        }
    }

    private void disableControls(string Object_Name)
    {
        switch (Object_Name.ToLower())
        {
            case "sy_report":
                txtReportName.Enabled = false;
                txtReportDesc.Enabled = false;
                rbTabular.Enabled = false;
                rbMatrix.Enabled = false;
                rbMasterDetail.Enabled = false;
                rbAllObjects.Enabled = false;
                rbPredefinedObjects.Enabled = false;
                break;
            case "sy_report_obj":
            case "sy_report_att":
                cmbObject.Enabled = false;
                lstFields.Enabled = false;
                lstSelectedFields.Enabled = false;
                imgSelect.Enabled = false;
                imgUnselect.Enabled = false;
                imgUp.Enabled = false;
                imgDown.Enabled = false;
                lblMsgStep2.Text = "You do not have sufficient access permission.";
                lblMsgStep2.ForeColor = System.Drawing.Color.Red;
                break;
            //case "sy_report_att":
            //    tblProperties.Disabled = true;
            //    lblMsgStep3.Text = "You do not have sufficient access permission.";
            //    lblMsgStep2.ForeColor = System.Drawing.Color.Red;
            //    break;
        }
    }

    private void getInputDataSet(ref DataSet dsInputInfo)
    {
        //foreach (DataRow dr in dsPageInfo.Tables["page"].Rows)
        //{
        string sObject_id = "sy_report";
        if (hdds.getObjectRightsForUser(sObject_id, "read"))
        {
            string sSql = "select * from sy_report where af_row_id = '" + m_PageKey + "'";
            DataTable dt = hdd.GetDataTable(sSql);
            dt.TableName = "p_sy_report";
            dsInputInfo.Tables.Add(dt.Copy());

            sObject_id = "sy_report_obj";
            if (hdds.getObjectRightsForUser("sy_report_obj", "read"))
            {
                sSql = "select * from sy_report_obj where rpt_id = '" + m_PageKey + "'";
                dt = hdd.GetDataTable(sSql, "p_sy_report_obj");
                dsInputInfo.Tables.Add(dt.Copy());
            }
            else
                disableControls(sObject_id);

            sObject_id = "sy_report_att";
            if (hdds.getObjectRightsForUser("sy_report_att", "read"))
            {
                sSql = "select * from sy_report_att where rpt_id = '" + m_PageKey + "'";
                dt = hdd.GetDataTable(sSql, "p_sy_report_att");
                dsInputInfo.Tables.Add(dt.Copy());
            }
            else
                disableControls(sObject_id);
        }
        else
            disableControls(sObject_id);
        //}
    }

    private bool getData()
    {
        dsInputInfo = new DataSet();

        getInputDataSet(ref dsInputInfo);

        if (IsEdit)
        {
            if (Session["ReportInput"] == null)
                Session.Add("ReportInput", dsInputInfo);
            else
                Session["ReportInput"] = dsInputInfo;
        }

        return true;
    }

    private bool setData(bool IsEdit)
    {
        if (dsInputInfo.Tables["p_sy_report"].Rows.Count == 0) return false;
        if (IsEdit)
            txt_Report_Id.Text = dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_id"].ToString();
        else
            txt_Report_Id.Text = getReportId();

        txtReportName.Text = dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_name"].ToString();
        txtReportDesc.Text = dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_desc"].ToString();
        //ddownerid.SelectedValue = dsInputInfo.Tables["p_sy_report"].Rows[0]["owner_id"].ToString();
        owner_id.Value = dsInputInfo.Tables["p_sy_report"].Rows[0]["owner_id"].ToString();
        LoadEditPage LEP = new LoadEditPage();
        txt_owner_id.Text = LEP.GetUserIDFromAfrowid(dsInputInfo.Tables["p_sy_report"].Rows[0]["owner_id"].ToString());
        LEP = null;

        switch (dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_type"].ToString().ToLower())
        {
            case "tabular":
                rbTabular.Checked = true;
                break;
            case "matrix":
                rbMatrix.Checked = true;
                break;
            case "master-detail":
                rbMasterDetail.Checked = true;
                break;
        }

        if (dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "true")
        {
            rbPredefinedObjects.Checked = true;
            rbAllObjects.Checked = false;
            loadSQLinCombo();
        }
        else
            rbAllObjects.Checked = true;

        //loadObjectsinCombo("select * from sy_obj");
        if (dsInputInfo.Tables.Contains("p_sy_report_obj"))
        {
            if (dsInputInfo.Tables["p_sy_report_obj"].Rows.Count > 0)
                cmbObject.Text = dsInputInfo.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString();
            //populateFields(cmbObject.Text);
        }

        if (dsInputInfo.Tables.Contains("p_sy_report_att"))
        {
            if (dsInputInfo.Tables["p_sy_report_att"].Rows.Count > 0)
            {
                populateListBox(lstFields);
                foreach (DataRow dr in dsInputInfo.Tables["p_sy_report_att"].Rows)
                {
                    ListItem li = lstFields.Items.FindByValue("[" + dr["object_id"].ToString() + "].[" + dr["attrib_id"].ToString() + "]");
                    //foreach (ListItem li in lstFields.Items)
                    //{
                    //if (li.Value == "[" + cmbObject.SelectedValue + "].[" + dr["attrib_id"].ToString() + "]")
                    //{
                    if (li != null)
                    {
                        lstFields.Items.Remove(li);
                        lstSelectedFields.Items.Add(li);
                    }
                    //break;
                    //}
                    //}
                }
                collectValuesFromDS();
            }
        }
        //dsInputInfo.Tables["p_report"].Rows[0]
        //Session.Add("ReportInput", dsInputInfo);
        imgSelectEnableDisable();
        
        GlobalValues.dsAudit = dsInputInfo;
        return true;
    }

    private void imgSelectEnableDisable()
    {
        if (lstFields.Items.Count == 0)
        {
            imgSelect.Enabled = false;
            imgSelectAll.Enabled = false;
            imgUnselect.Enabled = true;
            imgUnselectAll.Enabled = true;
            imgUp.Enabled = true;
            imgDown.Enabled = true;
        }
        else if (lstSelectedFields.Items.Count == 0)
        {
            imgSelect.Enabled = true;
            imgSelectAll.Enabled = true;
            imgUnselect.Enabled = false;
            imgUnselectAll.Enabled = false;
            imgUp.Enabled = false;
            imgDown.Enabled = false;
        }
        else
        {
            imgSelect.Enabled = true;
            imgSelectAll.Enabled = true;
            imgUnselect.Enabled = true;
            imgUnselectAll.Enabled = true;
            imgUp.Enabled = true;
            imgDown.Enabled = true;
        }
    }

    private string getFieldCaption(string LiValue)
    {
        string sCaption = "";
        try
        {
            if (dsInputInfo != null)
            {
                if (dsInputInfo.Tables.Contains("p_sy_report_att"))
                {
                    DataTable dtAtt = dsInputInfo.Tables["p_sy_report_att"];

                    if (dtAtt != null)
                    {
                        string sAttribId = LiValue.Substring(LiValue.IndexOf("].[") + 3, LiValue.Length - 1 - (LiValue.IndexOf("].[") + 3));
                        string sObjectId = LiValue.Substring(1, LiValue.IndexOf("]") - 1);
                        DataRow[] dr = dtAtt.Select("rpt_id='" + hf_af_row_id.Value + "' and object_id = '" + sObjectId + "' and attrib_id = '" + sAttribId + "'");

                        if (dr.Length != 0)
                        {
                            sCaption = dr[0]["caption"].ToString();
                        }
                    }
                }
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog(this.Title + " : Error : " + ex.Message);
        }
        return sCaption;
    }

    private string getReportId()
    {
        string sReportId = "1";

        try
        {
            string sTemp = hdd.GetColumnValue("Select max(rpt_id) from sy_report");
            if (sTemp != "")
                sReportId = Convert.ToString(Convert.ToInt16(sTemp) + 1);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getReportId : Error : " + ex.Message);
            return "1";
        }
        return sReportId;
    }

    protected void imgSelectAll_Click(object sender, ImageClickEventArgs e)
    {
        populateListBox(lstSelectedFields); //populateFields("", lstSelectedFields);
        imgUnselect.Enabled = true;
        imgUnselectAll.Enabled = true;
        imgUp.Enabled = true;
        imgDown.Enabled = true;
        if (lstFields.Items.Count == 0)
        {
            imgSelect.Enabled = false;
            imgSelectAll.Enabled = false;
        }
    }

    protected void imgUnselectAll_Click(object sender, ImageClickEventArgs e)
    {
        populateListBox(lstFields); //populateFields("", lstFields);
        imgSelect.Enabled = true;
        imgSelectAll.Enabled = true;
        if (lstSelectedFields.Items.Count == 0)
        {
            imgUnselect.Enabled = false;
            imgUnselectAll.Enabled = false;
            imgUp.Enabled = false;
            imgDown.Enabled = false;
        }
    }

    private void populateListBox(ListBox Fields)
    {

        if (rbAllObjects.Checked)
            populateFields("", Fields);
        else if (rbPredefinedObjects.Checked)
            populateFieldsFromQuery(Fields);
    }

    private string getWhereCondition(DataTable dtObject, DataTable dtFields, ref string sTableName)
    {
        string sWhere = "";
        DataRow[] drObjects = dtFields.Select("object_id <> '" + dtObject.Rows[0]["object_id"].ToString() + "'");
        if (drObjects.Length > 0)
        {
            string sMasterObject = getObjectName(drObjects[0]["object_id"].ToString());
            string sChildObject = getObjectName(dtObject.Rows[0]["object_id"].ToString());
            sWhere = "[" + sChildObject + "].[" + drObjects[0]["attrib_id"].ToString() + "]=[" + sMasterObject + "].[af_row_id]";
            sTableName = sMasterObject + "," + sChildObject;
        }
        return sWhere;
    }

    private string getCustodianFilter(string sTableName)
    {
        string sCustodian = "";
        try
        {
            string sSql = "select custodian_filter from sy_usr where af_row_id='" + Session["user_afrowid"].ToString() + "'";
            string sTemp = hdd.GetColumnValue(sSql);
            if (Session["userid"].ToString() == "afadmin")
            {
                sCustodian = "";
            }
            else if (sTemp.ToLower() == "ar" || Session["user_afrowid"].ToString() == "650a333596bbf348" || sTemp.Trim() == "")
            {
                ////sCustodian = Tablename + ".created_by != 'e51e0327224a2eb9'";
                //sCustodian = "[" + sTableName + "].created_by <> 'e51e0327224a2eb9'";
                // Added by srivatsan on June 15 2009 for owner id field
                sCustodian = "[" + sTableName + "].owner_id <> 'e51e0327224a2eb9'";
            }
            else if (sTemp.ToLower() == "mr")
            {
                //sCustodian = "[" + sTableName + "].created_by='" + Session["user_afrowid"].ToString() + "'";//sCustodian = "created_by='" + Session["user_afrowid"].ToString() + "'";
                // Added by srivatsan on June 15 2009 for owner id field
                sCustodian = "[" + sTableName + "].owner_id='" + Session["user_afrowid"].ToString() + "'";//sCustodian = "created_by='" + Session["user_afrowid"].ToString() + "'";
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCustodianFilter : Error : " + ex.Message);
        }
        return sCustodian;
    }

    private string getSql()
    {
        string sSql = "";
        if (dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "true")
        {
            string sSqlId = dsInputInfo.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString();
            sSql = getPredefinedSQL(sSqlId);
        }
        else
        {
            string sTableName = getObjectName(dsInputInfo.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString());
            string sFieldName = getFieldNames(dsInputInfo.Tables["p_sy_report_att"], sTableName);
            //string sCustodian = getCustodianFilter(sTableName);
            //string sWhereCondition = getWhereCondition(dsInputInfo.Tables["p_sy_report_obj"], dsInputInfo.Tables["p_sy_report_att"], ref sTableName);
            //string sRowLevelSecurity = hdds.getRowLevelSecurityData(sTableName, sTableName);
            //if (sCustodian != "")
            //    if (sWhereCondition != "")
            //        sWhereCondition = sWhereCondition + " and " + sCustodian;
            //    else
            //        sWhereCondition = sWhereCondition + " " + sCustodian;

            if (sFieldName != "")
            {
                sSql = "Select " + sFieldName + " from " + sTableName;
            }

            //if (sWhereCondition.Trim() != "")
            //{
            //    sSql = sSql + " where " + sWhereCondition;
            //}
            //else
                sSql = sSql + " where 1=1";

            //if (sRowLevelSecurity != "")
            //{
            //    sSql = sSql + " and " + sRowLevelSecurity;
            //}
        }

        return sSql;
    }

    private string getObjectName(string ObjectId)
    {
        HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
        string sObjectName = hdd.GetColumnValue("Select object_table from sy_obj where object_id = '" + ObjectId + "'");
        return sObjectName;
    }

    private string getPredefinedSQL(string SQL_id)
    {
        HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
        string sSQL = hdd.GetColumnValue("Select report_base_sql from sy_report_sql where report_base_id=" + SQL_id);
        Hashtable hsParam = new Hashtable();
        hsParam = getParameters("$", ref hsParam);
        hsParam = getParameters("#", ref hsParam);
        if ((sSQL.Contains("$") || sSQL.Contains("#")) && !IsPostBack)
        {
            //DrawParameterTable(ref hsParam);
            btn_Generate.Visible = true;
            lbFF.Visible = false;
            ddlFileFormat.Visible = false;
            lnkExport.Visible = false;
            //lnkPrint.Enabled = false;
            sSQL = "";
            hsParam = null;
        }
        else
            sSQL = ReplaceParameters(sSQL);
        return sSQL;
    }

    private string ReplaceParameters(string SQL)
    {
        Hashtable hsParam = new Hashtable();
        hsParam = getParameters("$", ref hsParam);
        hsParam = getParameters("#", ref hsParam);
        foreach (string sParam in hsParam.Keys)
        {
            if (sParam.StartsWith("#") && sParam.EndsWith("#"))
                SQL = SQL.Replace(sParam, GetLocalizedDateTime(sParam));
            else
                SQL = SQL.Replace(sParam, Request.Form["ctl00$ContentPlaceHolder3$wz_Report$txt_" + sParam]);
        }
        return SQL;
    }

    private string GetLocalizedDateTime(string sParam)
    {
        string sRet = "";
        try
        {
            sRet = Request.Form["ctl00$ContentPlaceHolder3$wz_Report$txt_" + sParam];
            #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
            //Localization li = new Localization();
            //DateTime dt = DateTime.Parse(sRet, li.getUserCulture());
            //sRet = dt.ToString();
            //li = null;
            #endregion
            sRet = DateTime.Parse(sRet, MBLocale.MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString())).ToString();
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("ReplaceDateTime : Error : " + Ex.Message);
            //sRet = Request.Form["ctl00$ContentPlaceHolder3$wz_Report$txt_" + sParam];
        }
        return sRet;
    }

    private string getUTCHours(string sUTC_Offset)
    {
        string sHours = "+0";
        try
        {
            if (sUTC_Offset != "")
            {
                if (sUTC_Offset.IndexOf(".") != -1)
                    sHours = sUTC_Offset.Substring(0, sUTC_Offset.IndexOf('.'));
                else
                    sHours = sUTC_Offset.Trim();

                sHours = sHours.Replace("+", "").Replace("-", "");

                if (sUTC_Offset.StartsWith("-"))
                    sHours = "-" + sHours;
                else
                    sHours = "+" + sHours;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getUTCHours : Error : " + ex.Message);
            return "+0";
        }
        return sHours;
    }

    private string getUTCMinutes(string sUTC_Offset)
    {
        string sMinutes = "+0";
        try
        {
            if (sUTC_Offset != "")
            {
                sMinutes = sUTC_Offset.Substring(sUTC_Offset.IndexOf('.') + 1, sUTC_Offset.Length - sUTC_Offset.IndexOf('.') - 1);

                sMinutes = sMinutes.Replace("+", "").Replace("-", "");

                if (sUTC_Offset.StartsWith("-"))
                    sMinutes = "-" + sMinutes;
                else
                    sMinutes = "+" + sMinutes;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getUTCMinutes : Error : " + ex.Message);
            return "+0";
        }
        return sMinutes;
    }

    private string getDTSQL(string ObjectName, string FieldName, string sHours, string sMinutes)
    {
        string sDateAdd = "";
        try
        {
            if (sMinutes != "")
                sDateAdd = "dateadd(mi, " + sMinutes + ", [" + ObjectName + "].[" + FieldName + "])";
            if (sHours != "")
            {
                if (sDateAdd == "")
                    sDateAdd = "dateadd(hh, " + sHours + ", [" + ObjectName + "].[" + FieldName + "])";
                else
                    sDateAdd = "dateadd(hh, " + sHours + "," + sDateAdd + ")";
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getDTSQL : Error : " + ex.Message);
            return FieldName;
        }
        return sDateAdd;
    }

    private string getUserIdSQL(string FieldName, string ObjectName)
    {
        string sUserSQL = "";
        try
        {
            sUserSQL = "(SELECT user_id AS " + FieldName + " from sy_usr as usr where (usr.af_row_id=" + ObjectName + "." + FieldName + ")) as " + FieldName + " ,";
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getUserIdSQL : Error : " + ex.Message);
            sUserSQL = FieldName;
        }

        return sUserSQL;
    }


    private string getFieldNames(DataTable dtAttribute, string sObjectName)
    {
        string sFields = "";
        //DynamicDisplayI DDI = new DynamicDisplayI();
        //string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");

        //string sHrs = getUTCHours(sUTC_Offset);
        //string sMins = getUTCMinutes(sUTC_Offset);

        //HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
        foreach (DataRow dr in dtAttribute.Rows)//Select("", "attrib_sequence asc")
        {
            string sAttrib_id = dr["attrib_id"].ToString();
            //if (sAttrib_id.ToLower() == "created_by" || sAttrib_id.ToLower() == "modified_by")
            //{
            //    sFields += getUserIdSQL(sAttrib_id, sObjectName);
            //}
            //else
            //{
            //    DataRow drMas_Det = hdd.GetTableRow("select * from sy_obj_mas_detail where master_obj='" + dr["object_id"].ToString() + "' and attrib_id = '" + sAttrib_id + "'");
            //    if (drMas_Det != null)
            //    {
            //        sAttrib_id = drMas_Det["display_att"].ToString();
            //    }
                //string sObject_name = getObjectName(dr["object_id"].ToString());
            //    string sDatatype = hdd.GetColumnValue("select attrib_data_type from sy_obj_att where object_id='" + hdd.GetColumnValue("select af_row_id from sy_obj where object_id='" + dr["object_id"].ToString() + "'") + "' and attrib_id = '" + sAttrib_id + "'");
            //    Localization li = new Localization();
            //    string sFormat = li.getDateTimeFormat();
            //    li = null;
            //    if (sDatatype == "DT")
            //    {
            //        string sDateAdd = getDTSQL(sObject_name, sAttrib_id, sHrs, sMins);
            //        sFields = sFields + sDateAdd + " as [" + sAttrib_id + "], ";
            //    }
            //    else
                    sFields = sFields + " [" + sObjectName + "].[" + sAttrib_id + "],"; //+ "] as [" + dr["caption"].ToString() + "], " ;
            //}
        }
        
        sFields = sFields.Trim();

        if (sFields.EndsWith(","))
            sFields = sFields.Trim(',');
        
        //if (sFields.EndsWith(","))
        //    sFields = sFields + "[" + sObjectName + "]." + "created_by as mb_c_by ";
        //else
        //    sFields = sFields + "," + "[" + sObjectName + "]." + "created_by as mb_c_by ";

            //sFields = sFields.Remove(sFields.Length - 1, 1);
        return sFields;
    }

    private string getReportProperties(string FieldName)
    {
        string sReportName = "";
        if (dsInputInfo.Tables["p_sy_report"] != null)
        {
            sReportName = dsInputInfo.Tables["p_sy_report"].Rows[0][FieldName].ToString();
        }
        return sReportName;
    }

    private void openReport()
    {
        if (fillInputData(ref dsInputInfo))
        {
            if (Session["ReportInput"] == null)
                Session.Add("ReportInput", dsInputInfo);
            else
                Session["ReportInput"] = dsInputInfo;
        }
        string popupScript = "<script language='javascript'>" +
            "(window.open('Report.aspx','ReportWindow'," +
            "'menubar=no,resizable=yes,scrollbars=yes," +
            "')||window).focus();" + "</script>";//height=600,width=800,top=50,left=100
        ClientScript.RegisterClientScriptBlock(imgNewWindow.GetType(), "ReportWindow", popupScript);
    }

    protected void imgNewWindow_Click(object sender, ImageClickEventArgs e)
    {
        switch (wz_Report.ActiveStepIndex)
        {
            case 0:
                break;
            case 1:
                if (cmbObject.Text == "--Select an Object--")
                {
                    lblFieldsMsg.Text = "Please select an object";
                    wz_Report.ActiveStepIndex = 1;
                }
                else if (lstSelectedFields.Items.Count == 0)
                {
                    if (rbPredefinedObjects.Checked)
                    {
                        DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + cmbObject.SelectedItem.Value);
                        if (dr != null)
                        {
                            if (!dr["report_base_sql"].ToString().Contains("$") && !dr["report_base_sql"].ToString().Contains("#"))
                            {
                                lblFieldsMsg.Text = "Please select atleast one field to be displayed in the report";
                                wz_Report.ActiveStepIndex = 1;
                            }
                            else
                                openReport();
                        }
                    }
                    else
                    {
                        lblFieldsMsg.Text = "Please select atleast one field to be displayed in the report";
                        wz_Report.ActiveStepIndex = 1;
                    }
                }
                else
                {
                    //FillSelectedFields();
                    openReport();
                }
                break;
            case 2:
            case 3:
                openReport();
                break;
        }
    }
    protected void btnFinish_Click(object sender, EventArgs e)
    {
        try
        {
            if (!validateOwnerid())
            {
                return;
            }

            switch (wz_Report.ActiveStepIndex)
            {
                case 0:
                    break;
                case 1:
                    if (cmbObject.Text == "--Select an Object--")
                    {
                        lblFieldsMsg.Text = "Please select an object";
                        wz_Report.ActiveStepIndex = 1;
                    }
                    else if (lstSelectedFields.Items.Count == 0)
                    {
                        if (rbPredefinedObjects.Checked)
                        {
                            DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + cmbObject.SelectedItem.Value);
                            if (dr != null)
                            {
                                if (dr["report_base_sql"].ToString().Contains("$") || dr["report_base_sql"].ToString().Contains("#"))
                                    SaveDataforFinish();
                            }
                        }
                        else
                        {
                            lblFieldsMsg.Text = "Please select atleast one field to be displayed in the report";
                            wz_Report.ActiveStepIndex = 1;
                        }
                    }
                    else
                    {
                        //FillSelectedFields();
                        SaveDataforFinish();
                    }
                    break;
                case 2:
                    SaveDataforFinish();
                    break;
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("btnFinish_Click : Error : " + Ex.Message);
        }
    }

    private void FillSelectedFields()
    {
        populateListBox(lstSelectedFields); //populateFields("", lstSelectedFields);
        imgUnselect.Enabled = true;
        imgUnselectAll.Enabled = true;
        imgUp.Enabled = true;
        imgDown.Enabled = true;
        if (lstFields.Items.Count == 0)
        {
            imgSelect.Enabled = false;
            imgSelectAll.Enabled = false;
        }
    }

    private void SaveDataforFinish()
    {
        if (fillInputData(ref dsInputInfo))
        {

            if (IsEdit)
            {
                updateData(ref dsInputInfo);
            }
            else
            {
                string sOperation = "INSERT";
                Master objMaster = new Master();

                if (!objMaster.ProcessOperation(dsPageInfo, dsInputInfo, sOperation))
                    lblMessage.Text = objMaster.ErrorMessage;
            }
        }
        //deleteReport();        

        if (Session["ReportInput"] != null)
            Session.Remove("ReportInput");

        Response.Redirect(Session["RedirectLocation"].ToString(),false);
    }
    protected void ddlFileFormat_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlFileFormat.SelectedIndex != 0)
            lnkExport.Enabled = true;
        else
            lnkExport.Enabled = false;
    }

    private void Print()
    {
        try
        {
            if (m_streams == null || m_streams.Count == 0)
                return;
            PrintDocument printDoc = new PrintDocument();
            PrinterSettings ps = new PrinterSettings();

            if (printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ps.PrinterName = printDialog1.PrinterSettings.PrinterName;
                ps.Copies = printDialog1.PrinterSettings.Copies;
                ps.DefaultPageSettings.Color = printDialog1.PrinterSettings.DefaultPageSettings.Color;
                ps.DefaultPageSettings.Landscape = printDialog1.PrinterSettings.DefaultPageSettings.Landscape;
                ps.DefaultPageSettings.Margins = printDialog1.PrinterSettings.DefaultPageSettings.Margins;
                ps.DefaultPageSettings.PaperSize = printDialog1.PrinterSettings.DefaultPageSettings.PaperSize;
                ps.DefaultPageSettings.PaperSource = printDialog1.PrinterSettings.DefaultPageSettings.PaperSource;
                ps.DefaultPageSettings.PrinterResolution = printDialog1.PrinterSettings.DefaultPageSettings.PrinterResolution;
                ps.DefaultPageSettings.PrinterSettings = printDialog1.PrinterSettings.DefaultPageSettings.PrinterSettings;
                ps.Duplex = printDialog1.PrinterSettings.Duplex;
                ps.FromPage = printDialog1.PrinterSettings.FromPage;
                ps.MaximumPage = printDialog1.PrinterSettings.MaximumPage;
                ps.MinimumPage = printDialog1.PrinterSettings.MinimumPage;
                ps.PrintFileName = printDialog1.PrinterSettings.PrintFileName;
                ps.PrintRange = printDialog1.PrinterSettings.PrintRange;
                ps.PrintToFile = printDialog1.PrinterSettings.PrintToFile;
                ps.ToPage = printDialog1.PrinterSettings.ToPage;

                printDoc.PrinterSettings = ps;

                if (!printDoc.PrinterSettings.IsValid)
                {
                    string msg = String.Format("Can't find printer \"{0}\".", printDialog1.PrinterSettings.PrinterName);
                    return;
                }
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                printDoc.Print();
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("Print : Error : " + ex.Message);
        }
    }

    private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
    {
        Stream stream = null;
        try
        {
            stream = new FileStream(name + "." + fileNameExtension,
                FileMode.Create);
            m_streams.Add(stream);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("CreateStream : Error : " + ex.Message);
        }
        return stream;
    }


    /// <summary>
    /// Export the given report as an EMF (Enhanced Metafile) file.
    /// </summary>
    private void Export(Microsoft.Reporting.WebForms.LocalReport report, string PageWidth, float PageHeight, float MarginTop, float MarginLeft, float MarginRight, float MarginBottom)
    {
        try
        {
            StringBuilder deviceInfosb = new StringBuilder();
            deviceInfosb.Append("<DeviceInfo>");
            deviceInfosb.Append("<OutputFormat>EMF</OutputFormat>");
            deviceInfosb.Append(string.Format("<PageWidth>{0}in</PageWidth>", PageWidth));
            deviceInfosb.Append(string.Format("<PageHeight>{0}in</PageHeight>", PageHeight));
            deviceInfosb.Append(string.Format("<MarginTop>{0}in</MarginTop>", MarginTop));
            deviceInfosb.Append(string.Format("<MarginLeft>{0}in</MarginLeft>", MarginLeft));
            deviceInfosb.Append(string.Format("<MarginRight>{0}in</MarginRight>", MarginRight));
            deviceInfosb.Append(string.Format("<MarginBottom>{0}in</MarginBottom>", MarginBottom));
            deviceInfosb.Append(string.Format("</DeviceInfo>"));
            string deviceInfo = deviceInfosb.ToString();
            Microsoft.Reporting.WebForms.Warning[] warnings;
            m_streams = new List<Stream>();
            //Warning[] warnings;
            //string[] streamids;
            //string mimeType;
            //string encoding;
            //string filenameExtension;
            //report.Render("Image", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
            report.Render("Image", deviceInfo, CreateStream, out warnings);
            foreach (Stream stream in m_streams)
            {
                stream.Position = 0;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("Export : Error : " + ex.Message);
        }
    }

    /// <summary>
    /// Handler for PrintPageEvents
    /// </summary>
    private void PrintPage(object sender, PrintPageEventArgs ev)
    {
        try
        {
            System.Drawing.Imaging.Metafile pageImage = new System.Drawing.Imaging.Metafile(m_streams[m_currentPageIndex]);
            ev.Graphics.DrawImage(pageImage, ev.PageBounds);
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("PrintPage : Error : " + ex.Message);
        }
    }

    protected void Page_SaveStateComplete(object sender, EventArgs e)
    {
        try
        {
            if (bExport)
            {
                if (ddlFileFormat.SelectedIndex != 0)
                {
                    ReportPrintHelper oPrint = new ReportPrintHelper();
                    switch (ddlFileFormat.SelectedValue)
                    {
                        case "Excel":
                            oPrint.ExportReport(ref rptViewer, EXPORT_TYPE.TYPE_XLS, Context, true, HttpContext.Current.Session["ReportWidth"].ToString());
                            break;
                        case "PDF":
                            oPrint.ExportReport(ref rptViewer, EXPORT_TYPE.TYPE_PDF, Context, true, HttpContext.Current.Session["ReportWidth"].ToString());
                            break;
                    }
                    oPrint = null;
                    ddlFileFormat.SelectedValue = "";
                    bExport = false;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Page_SaveStateComplete : Error : " + ex.Message);
        }
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        bExport = true;
    }
    protected void lnkPrint_Click(object sender, EventArgs e)
    {
        try
        {
            Microsoft.Reporting.WebForms.LocalReport report = rptViewer.LocalReport;
            Export(report, HttpContext.Current.Session["ReportWidth"].ToString() /*dReportWidth*/, 8.27f, 0.3f, 0.3f, 0.3f, 0.3f);//Export(report, 11.69f, 8.27f, 0f, 0f, 0f, 0f);
            m_currentPageIndex = 0;

            Print(); foreach (Stream s in m_streams)
            {
                s.Close();
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("lnkPrint_Click : Error : " + ex.Message);
        }
    }

    private Hashtable getParameters(string sChar, ref Hashtable hsParam)
    {
        //Hashtable hsParam = new Hashtable();
        try
        {
            DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + cmbObject.SelectedItem.Value);
            if (dr != null)
            {
                string sSql = dr["report_base_sql"].ToString();
                int iPos = 0;

                while (iPos < sSql.Length & iPos != -1)
                {
                    string sParam = "";
                    iPos = sSql.IndexOf(sChar,iPos);
                    if (iPos != -1)
                    {
                        int iEndPos = sSql.IndexOf(sChar, iPos + 1);
                        if (iEndPos == -1)
                            iEndPos = sSql.Length - iPos;
                        else
                            iEndPos = iEndPos - (iPos - 1);
                        sParam = sSql.Substring(iPos, iEndPos);
                        sParam = sParam.TrimEnd('\'');
                        if (!hsParam.Contains(sParam))
                            hsParam.Add(sParam, "");
                        iPos = iPos + iEndPos;
                    }
                }

                /*hsParam = getParameters("#", ref hsParam);
                return hsParam;*/
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("getParameters : Error : " + Ex.Message);
        }

        return hsParam;
    }

    private void DrawParameterTable(ref Hashtable hsParam)
    {
        try
        {
            if (hsParam.Count > 0)
            {
                DynamicDisplayI DDI = new DynamicDisplayI();
                HtmlTableCell ht = (HtmlTableCell)DDI.FindControl(this.Controls, "td_param");
                DDI = null;
                if (ht != null)
                {
                    HtmlTable htTable = new HtmlTable();
                    htTable.CellSpacing = 1;
                    htTable.CellPadding = 2;
                    htTable.Attributes.Add("runat", "server");
                    HtmlTableRow htr = new HtmlTableRow();
                    HtmlTableCell htc = new HtmlTableCell();
                    htr.Attributes.Add("class", "Grid_Header");
                    htc = new HtmlTableCell();
                    htc.InnerText = "Parameter   ";
                    htr.Cells.Add(htc);
                    htc = new HtmlTableCell();
                    htc.InnerText = "Value";
                    htr.Cells.Add(htc);
                    htTable.Rows.Add(htr);
                    foreach (string sParam in hsParam.Keys)
                    {
                        htr = new HtmlTableRow();
                        htc = new HtmlTableCell();
                        htr.Attributes.Add("class", "controlFont");
                        htc.InnerText = sParam.Replace("$", "").Replace("#", "") + "   ";
                        htr.Cells.Add(htc);
                        htc = new HtmlTableCell();
                        TextBox txt = new TextBox();
                        txt.ID = "txt_" + sParam;
                        //txt.Width = Unit.Parse("100");
                        htc.Controls.Add(txt);
                        htr.Cells.Add(htc);
                        htTable.Rows.Add(htr);
                    }
                    ht.Controls.Add(htTable);
                }
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("DrawParameterTable : Error : " + Ex.Message);
        }
    }

    private void SetParameter(ref Hashtable hsParam)
    {
        try
        {
            DynamicDisplayI DDI = new DynamicDisplayI();
            foreach (string sParam in hsParam.Keys)
            {
                TextBox txt = (TextBox)DDI.FindControl(this.Controls, "txt_" + sParam);
                if (txt != null)
                {
                    txt.Text = Request.Form["ctl00$ContentPlaceHolder3$wz_Report$txt_" + sParam];
                }
            }
            DDI = null;
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("SetParameter : Error : " + Ex.Message);
        }
    }
    protected void btn_Generate_Click(object sender, EventArgs e)
    {
        //DynamicDisplayI DDI = new DynamicDisplayI();
        //DDI.FindControl(this.Controls,"ctl00$ContentPlaceHolder3$wz_Report$txt_$object_id");
        //DDI = null;
        //this.wz_Report.FindControl("ctl00$ContentPlaceHolder3$wz_Report$txt_$object_id")
        GenerateReport();
    }

    private void GenerateReport()
    {
        string sReportName = null;
        //string absReportPath = null;

        try
        {
            ImageButton newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
            //newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
            newWindow.Visible = true;
            //getData();
            if (fillInputData(ref dsInputInfo))
            {
                imgNewWindow.Enabled = true;
                if (Session["ReportInput"] == null)
                    Session.Add("ReportInput", dsInputInfo);
                else
                    Session["ReportInput"] = dsInputInfo;

                string constr = Session["dbcon"].ToString();
                
                string sSql = getSql();
                sReportName = getReportProperties("rpt_name");
                if (sReportName == "") sReportName = getReportProperties("rpt_id");
                //this.Title = "MaxBlox - Report - " + sReportName;
                //string sReportType = getReportProperties("rpt_type");
                SqlDataSource1.ConnectionString = constr;
                SqlDataSource1.SelectCommand = sSql;
                MyRDLC mrdlc = new MyRDLC();
                //mrdlc.serverPath = Server.MapPath("mystyle.txt");
                //int ind = mrdlc.serverPath.LastIndexOf('\\');
                //mrdlc.serverPath = mrdlc.serverPath.Substring(0, ind);
                //mrdlc.connectionString = constr;
                //mrdlc.OpenConnection();

                //bool bHasRows = mrdlc.GenerateFieldsList(sSql);
                //mrdlc.init();

                //string sTempReportName = sReportName + "_" + HttpContext.Current.Session["userid"].ToString() + "_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
                //if (!System.IO.Directory.Exists(mrdlc.serverPath + "\\report"))
                //System.IO.Directory.CreateDirectory(mrdlc.serverPath + "\\report");
                //absReportPath = mrdlc.serverPath + "\\report\\" + sTempReportName + ".rdlc";
                //mrdlc.commandText = sSql;
                //mrdlc.writeInitRDLC(absReportPath);
                //mrdlc.writeDataSource("DataSource1");
                //mrdlc.writeReportParameter();
                //mrdlc.writeDataset();

                //if (sReportType == "") sReportType = "tabular";
                //switch (sReportType.ToLower())
                //{
                //    default:
                //    case "tabular":
                //        mrdlc.GenerateRdl(absReportPath, sReportName, getReportProperties("rpt_desc"));
                //        break;
                //    //    /*case "matrix":
                //    //        mrdlc.GenerateMatrixRdl(absReportPath);
                //    //        break;*/
                //}

                MemoryStream msReport = null;
                //mrdlc.writeEndRDLC(ref msReport, absReportPath);
                float dReportWidth = 8.0f;
                if (dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "true")
                {
                    //DataTable dt = getDataTable(sSql);
                    getDataFromSQLandFormat objData = new getDataFromSQLandFormat(sSql);
                    DataTable dt = objData.getData(ref dsInputInfo);
                    objData = null;
                    if (dt != null)
                    {
                        mrdlc.GenerateReportFromDataset(dsInputInfo, ref msReport, ref dReportWidth, exportType);
                        rptViewer.LocalReport.DataSources.Clear();
                        rptViewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", dt));
                        rptViewer.Visible = true;
                        rptViewer.LocalReport.DisplayName = sReportName;
                        rptViewer.LocalReport.LoadReportDefinition(msReport);
                        rptViewer.LocalReport.EnableExternalImages = true;
                        rptViewer.LocalReport.Refresh();
                        msReport.Dispose();
                    }
                }
                else
                {
                    getDataFromSQLandFormat objData = new getDataFromSQLandFormat(sSql);
                    DataTable dt1 = objData.getData(ref dsInputInfo);
                    objData = null;
                    dsInputInfo.Tables.Add(dt1.Copy());
                    mrdlc.GenerateReportFromDataset(dsInputInfo, ref msReport, ref dReportWidth, exportType);
                    rptViewer.LocalReport.DataSources.Clear();
                    rptViewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", dt1));
                    dt1.Dispose();
                    dt1 = null;
                }
                /*mrdlc.GenerateReportFromDataset(dsInputInfo, ref msReport, ref dReportWidth);
                if (msReport != null)
                {
                    //this.Title = sReportName;
                    rptViewer.Reset();
                    rptViewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", "SqlDataSource1"));

                    if (dsInputInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "true")
                    {
                        DataTable dt = getDataForReport(sSql);
                        if (dt != null)
                        {
                            rptViewer.LocalReport.DataSources.Clear();
                            rptViewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", dt));
                        }
                    }
                    rptViewer.Visible = true;
                    rptViewer.LocalReport.DisplayName = sReportName;
                    rptViewer.LocalReport.LoadReportDefinition(msReport);
                    rptViewer.LocalReport.EnableExternalImages = true;
                    //absReportPath = @"D:\MaxBlox\app_frame\report\New_admin_200813144846721.rdlc";
                    //rptViewer.LocalReport.ReportPath = absReportPath;
                    rptViewer.LocalReport.Refresh();
                    msReport.Dispose();
                }*/
                //hfRName.Value = absReportPath;
                /*if (Session["ReportPath"] == null)
                    Session.Add("ReportPath", absReportPath);
                else
                    Session["ReportPath"] = absReportPath;*/
            }
            bool IsExport = getExportValue();
            if (IsExport)
            {
                lbFF.Visible = true;
                ddlFileFormat.Visible = true;
                lnkExport.Visible = true;
                //lnkPrint.Visible = true;
            }
            else
            {
                lbFF.Visible = false;
                ddlFileFormat.Visible = false;
                lnkExport.Visible = false;
                //lnkPrint.Visible = false;
            }
        }

        catch (Exception ex)
        {
            lbFF.Visible = false;
            ddlFileFormat.Visible = false;
            lnkExport.Visible = false;
            //lnkPrint.Enabled = false;
            imgNewWindow.Enabled = false;
            LogWriter.WriteLog("Error : " + ex.Message);
            Response.Redirect("Error.aspx");
        }
    }

    private bool getExportValue()
    {
        bool ret = false;
        HDDatabase hd = new HDDatabase();
        try
        {
            DataTable dt = hd.GetDataTable("select * from sy_acr_mem where af_row_id='" + "76cf74c043053300" + "'");
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    ret = dt.Rows[0]["mem_value1"].ToString().ToLower() == "true";
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in getExportValue: " + e.Message);
        }
        finally
        {
            hd = null;
        }
        return ret;
    }

    private void getpageicons() // added by srivatsan to get page icons
    {
        PageIcons icons = new PageIcons();
        HDDatabase HDD = new HDDatabase();
        try
        {
            //wz_Report.HeaderText = "&nbsp;" + icons.geticontextfrompageset(Request.QueryString["pgs_id"].ToString(), 2) + "&nbsp;" + wz_Report.HeaderText;
            Label lblcontrol = (Label)this.Master.FindControl("ctl00$ContentPlaceHolder3$wz_Report$HeaderContainer$Label3");
            lblcontrol.Text = "&nbsp;" + icons.geticontextfrompageset(Request.QueryString["pgs_id"].ToString(), 2) + "&nbsp;" + lblcontrol.Text;
          
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
           //wz_Report.HeaderText = "&nbsp;<img src =Images/MBIcons/small/default.gif><img>&nbsp;"+ wz_Report.HeaderText;

        }
        finally
        {
            icons = null;
            HDD = null;
        }
    }

    private void loadOwneridDropDown() // Added by srivatsan for owner id change
    {
        HDDatabase Hdd = new HDDatabase();
        BindControl BC = new BindControl();
        //DataSet ds = new DataSet();
        DataTable dt = null;
        try
        {
            //string bindid = Hdd.GetColumnValue("select mem_value3 from sy_acr_mem where acr_id = 'cee69885ce44589c' and mem_id = 'owner_id'");
            //BC.Bind(bindid, ddownerid, ref dt);

            //if (Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
           // {
                //ddownerid.Items.Add(new ListItem(Session["userid"].ToString(), Session["user_afrowid"].ToString()));
           // }

            if (Request.QueryString["PK"] == null)
            {
                //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                owner_id.Value = Session["user_afrowid"].ToString();
                txt_owner_id.Text = Session["userid"].ToString();
            }
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                    owner_id.Value = Session["user_afrowid"].ToString();
                    txt_owner_id.Text = Session["userid"].ToString();
                }

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
        }
        finally
        {
            Hdd = null;
            BC = null;
            dt = null;
        }


    }

    
    private bool validateOwnerid()
    {
        bool status = false;
        HDDatabase HDD = new HDDatabase();
        BindControl BC = new BindControl();
        
        DataSet dsBind = new DataSet();
        string sql = BC.GetBindSql("f496930dfe0b690f");
        dsBind = HDD.GetDataset(sql);
                           if (dsBind != null)
                            {
                                if (dsBind.Tables.Count > 0)
                                {
                                    if (dsBind.Tables[0].Rows.Count > 0)
                                    {
                                        DataRow[] drrbind = dsBind.Tables[0].Select("fld = '" + txt_owner_id.Text.Trim().Replace("'", "''") + "'");
                                        if (txt_owner_id.Text.Trim() != "")
                                        {
                                            if (drrbind.Length > 0)
                                            {
                                                owner_id.Value = drrbind[0]["val"].ToString();
                                                status = true;
                                            }
                                        }
                                        else
                                        {
                                            status = true;
                                            owner_id.Value = "";
                                        }
                                    }
                                    else
                                    {
                                        status = true;
                                        owner_id.Value = "";
                                    }
                                }
                            }
                            if (status != true)
                            {
                                lblMessage.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                                lblmessage2.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                                lblFieldsMsg.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                            }
                            return status;                                                
                                            
    }

    private string getUseraf_row_idfromUser(string userid)
    {
        string result = "";
        try
        {
            string sql = "select af_row_id from sy_usr where user_id = '"+userid+"'";
            result = hdd.GetColumnValue(sql);
        }
        catch
        {

        }

        return result;

    }

    private string applysecurity(string sql)
    {

        try
        {
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            string sCustodianFilter = objSec.QueryForCustodianFilter();
            if (sCustodianFilter.Trim() != "")
                if (!sCustodianFilter.StartsWith("or"))
                {
                    sAFAdmin += " and " + sCustodianFilter;
                }
                else
                {
                    //if (QuickSearchSQL.Trim() == "")  // if no search exists show all no owner records
                    //{
                    sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                    //sAFAdmin += " " + sCustodianFilter;
                    // }
                }

            if (sql.Contains("order by"))
            {
                if (sAFAdmin.Trim() != "")
                {
                    sql = sql.Replace("order by", "where " + sAFAdmin + " order by");
                }
            }
            else
            {
                if (sAFAdmin.Trim() != "")
                {
                    sql = sql + " where " + sAFAdmin;
                }
            }


        }
        catch
        {

        }
        return sql;
    }

    private void CheckForChangeOwner()  // Added by srivatsan to Check if user can change owner
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects(HttpContext.Current.Request.QueryString["pgs_id"].ToString(), "change_owner");
            if (status == false)
            {

             txt_owner_id.Enabled = false;
                imgsearch.Visible = false;
            }

            sec = null;
        }
        catch
        {

        }
    }

    private void IsActionMode()
    {

        try
        {
            if (Request.QueryString["action"] != null)
            {
                if (Request.QueryString["action"].ToString() == "1")
                {

                    NameValueCollection querystring = HttpUtility.ParseQueryString(Request.UrlReferrer.Query);
                        string strPagesetRowId = querystring["pgs_id"];
                        string strMenuRowId = querystring["mn"];
                        string strPK = Request.QueryString["ID"].ToString();
                        string temp = querystring["test"];
                    if (Request.QueryString["Vmode"] != null)
                    {
                        //Response.Redirect("ReportWizard.aspx?pgs_id=" + strPagesetRowId + "&PK=" + strPK + "&mn=" + strMenuRowId + "&vmode=1");
                        string redirect = "ReportWizard.aspx?pgs_id=6421de320e189de8&mn=613e91a1131935a0&PK=" + strPK + "&vmode=1"; //pgs_id=ps_report
                        Response.Redirect(redirect);
                    }
                    else if(Request.QueryString["PK"]==null)
                    {
                        Response.Redirect("ReportWizard.aspx?mn=613e91a1131935a0&pgs_id=6421de320e189de8");
                    }
                }
            }

        }
        catch(Exception ex)
        {

        }
    }

    /// <summary>
    /// This will add default Objects from sy_acr_mem to DataTable
    /// </summary>
    /// <param name="ddlObj"></param>
    private void AddDefaultObjects(ref DataTable dtInput)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            string objectids = "";
            if (dtInput != null)
            {
                foreach (DataRow dr in dtInput.Rows)
                {
                    objectids += "'"+dr["object_id"].ToString()+"',";
                }
                if (objectids.EndsWith(","))
                    objectids = objectids.TrimEnd(',');
            }
            string strSQL = "select mem_id,mem_name from sy_acr_mem where acr_id = '1b8bcdd101823723' and mem_value1 = 'true' and mem_value1 not in ("+objectids+") order by mem_name";
            DataTable dt = HDD.GetDataTable(strSQL);

            if (dt != null)
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow drInput = dtInput.NewRow();
                        drInput["object_name"] = dr["mem_name"].ToString();
                        drInput["object_id"] = dr["mem_id"].ToString();
                        dtInput.Rows.Add(drInput);
                    }
                }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddDefaultObjects : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }
}
